package cn.wit.summit.chwan.ui.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.adapters.FragmentPagerAdapter;
import cn.wit.summit.chwan.adapters.ImageListTopBarAdapter;
import cn.wit.summit.chwan.models.response.PicCollectionTypeListResponse;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.ui.base.BaseActivity;
import cn.wit.summit.chwan.ui.fragment.ImageCollectionFragment;
import cn.wit.summit.chwan.utils.PhotoSelectUtils;
import cn.wit.summit.chwan.widgets.SmoothScrollLayoutManager;
import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;
import retrofit2.Retrofit;

/**
 * Created by Alan on 2018/7/14.
 */

public class ImageCollectionActivity extends BaseActivity implements ImageListTopBarAdapter.OnChangeItem {

    @Bind(R.id.imageListViewPager)
    ViewPager imageListViewPager;
    @Bind(R.id.imageListTabRv)
    RecyclerView imageListTabRv;

    private SmoothScrollLayoutManager layoutManager;
    private ImageListTopBarAdapter imageAdapter;
    private List<ImageListTopBarAdapter.ViewBean> datas = new ArrayList<>();
    private List<FragmentPagerAdapter.Item> items = new ArrayList<>();

    private RetrofitManager retrofitManager;
    private Retrofit retrofit;
    private ApiUtil api;

    private String gameId;
    private int position;
    private int mPosition;
    private List<PicCollectionTypeListResponse.PicListBean> mData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        actionBarStyle = ACTION_BAR_NORMAL;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_collection);
        ButterKnife.bind(this);

        // 1、创建PhotoSelectUtils（一个Activity对应一个PhotoSelectUtils）
        mPhotoSelectUtils = new PhotoSelectUtils(this
                , new PhotoSelectUtils.PhotoSelectListener() {
            @Override
            public void onFinish(File outputFile, Uri outputUri) {
                // 4、当拍照或从图库选取图片成功后回调
                toUpImageActivity(outputFile.getPath());
            }
        }, false);//true裁剪，false不裁剪

        setBarTitleTx(R.string.pic_list_title);
        gameId = getIntent().getStringExtra("gameId");
        position = getIntent().getIntExtra("position", 0);
        mPosition = position;

        retrofitManager = RetrofitManager.getInstance(mContext);
        retrofit = retrofitManager.getRetrofit();
        api = retrofit.create(ApiUtil.class);

//        showSkeleton();
        getWebData();
    }

    private void getWebData() {
        api.getPicTypeList(gameId).enqueue(new MyCallback<ResponseBase<PicCollectionTypeListResponse>>() {
            @Override
            public void onSuccess(ResponseBase<PicCollectionTypeListResponse> model) {
//                hideSkeleton();
                PicCollectionTypeListResponse data = model.getData_info();
                initViewPager(data);
            }

            @Override
            public void onFailure(int code, String msg) {
//                hideSkeleton();
                showToast(msg);
            }
        });
    }

    private void initViewPager(PicCollectionTypeListResponse data) {
        if (data == null || data.getTypeList() == null || data.getTypeList().size() == 0) {
            showToast(mContext.getResources().getString(R.string.get_data_error));
            return;
        }

        mData = data.getTypeList();

        items.clear();
        datas.clear();
        for (int i = 0; i < data.getTypeList().size(); i++) {
            ImageCollectionFragment tempFragment = ImageCollectionFragment.newInstance(data.getTypeList().get(i), gameId, i);
            items.add(new FragmentPagerAdapter.Item(data.getTypeList().get(i).getTitle(), tempFragment));
            datas.add(new ImageListTopBarAdapter.ViewBean(ImageListTopBarAdapter.ViewType.TYPE_BASE, data.getTypeList().get(i)));
        }
        FragmentPagerAdapter adapter = new FragmentPagerAdapter(getSupportFragmentManager(), items);
        imageListViewPager.setAdapter(adapter);
        imageListViewPager.setOffscreenPageLimit(3);
        imageListViewPager.setCurrentItem(position);
        imageListViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                imageListTabRv.smoothScrollToPosition(position);
                imageAdapter.setSelectId(position);
                mPosition = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });

        layoutManager = new SmoothScrollLayoutManager(mContext);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        imageListTabRv.setLayoutManager(layoutManager);
        imageAdapter = new ImageListTopBarAdapter(mContext, datas, position, this);
        imageListTabRv.setAdapter(imageAdapter);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                imageListTabRv.smoothScrollToPosition(position);
            }
        }, 200);
    }

    @Override
    public void onchange(int position) {
        mPosition = position;
        imageListViewPager.setCurrentItem(position);
    }

    @Override
    protected int getSkeletonLayoutId() {
        return R.layout.activity_game_starter_skeleton;
    }

    @OnClick({R.id.imageListUpImageTv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.imageListUpImageTv:
                if (mData==null || mData.size()==0) {
                    return;
                }

                ChangIcon();
                break;
        }
    }

    private Dialog mPicChsDialog;

    private void ChangIcon() {
        mPicChsDialog = new Dialog(mContext, R.style.floate_dialog);
        mPicChsDialog.setContentView(R.layout.dialog_pic_choose);
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        Window dlgwin = mPicChsDialog.getWindow();
        WindowManager.LayoutParams lp = dlgwin.getAttributes();
        dlgwin.setGravity(Gravity.BOTTOM);
        lp.width = display.getWidth(); //设置宽度
        mPicChsDialog.getWindow().setAttributes(lp);
        TextView camera = (TextView) mPicChsDialog.findViewById(R.id.chos_camera);
        TextView picLib = (TextView) mPicChsDialog.findViewById(R.id.pic_lib);
        TextView cancel = (TextView) mPicChsDialog.findViewById(R.id.btn_cancel);
        camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPicChsDialog.dismiss();
                PermissionGen.with(mAty)
                        .addRequestCode(PhotoSelectUtils.REQ_TAKE_PHOTO)
                        .permissions(Manifest.permission.READ_EXTERNAL_STORAGE,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.CAMERA
                        ).request();
            }
        });

        picLib.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPicChsDialog.dismiss();
                PermissionGen.needPermission(mAty,
                        PhotoSelectUtils.REQ_SELECT_PHOTO,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE}
                );
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPicChsDialog.dismiss();
            }
        });
        mPicChsDialog.show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 2、在Activity中的onActivityResult()方法里与LQRPhotoSelectUtils关联
        mPhotoSelectUtils.attachToActivityForResult(requestCode, resultCode, data);
    }

    private void toUpImageActivity(String filePath) {
        Intent intent = new Intent(mContext, UpLoadImageActivity.class);
        intent.putExtra("filePath", filePath);
        intent.putExtra("gameId", gameId);
        intent.putExtra("mPosition", mPosition);
        Bundle bundle = new Bundle();
        bundle.putSerializable("mData",(Serializable)mData);
        intent.putExtras(bundle);
        startActivity(intent);

    }

    private PhotoSelectUtils mPhotoSelectUtils;
    @PermissionSuccess(requestCode = PhotoSelectUtils.REQ_TAKE_PHOTO)
    private void takePhoto() {
        mPhotoSelectUtils.takePhoto();
    }

    @PermissionSuccess(requestCode = PhotoSelectUtils.REQ_SELECT_PHOTO)
    private void selectPhoto() {
        mPhotoSelectUtils.selectPhoto();
    }

    @PermissionFail(requestCode = PhotoSelectUtils.REQ_TAKE_PHOTO)
    private void showTip1() {
        //        Toast.makeText(getApplicationContext(), "不给我权限是吧，那就别玩了", Toast.LENGTH_SHORT).show();
        showDialog();
    }

    @PermissionFail(requestCode = PhotoSelectUtils.REQ_SELECT_PHOTO)
    private void showTip2() {
        //        Toast.makeText(getApplicationContext(), "不给我权限是吧，那就别玩了", Toast.LENGTH_SHORT).show();
        showDialog();
    }

    public void showDialog() {
        //创建对话框创建器
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        //设置对话框显示小图标
        builder.setIcon(android.R.drawable.ic_dialog_alert);
        //设置标题
        builder.setTitle("权限申请");
        //设置正文
        builder.setMessage("在设置-应用-虎嗅-权限 中开启相机、存储权限，才能正常使用拍照或图片选择功能");

        //添加确定按钮点击事件
        builder.setPositiveButton("去设置", new DialogInterface.OnClickListener() {//点击完确定后，触发这个事件

            @Override
            public void onClick(DialogInterface dialog, int which) {
                //这里用来跳到手机设置页，方便用户开启权限
                Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS);
                intent.setData(Uri.parse("package:" + mAty.getPackageName()));
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });

        //添加取消按钮点击事件
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });

        //使用构建器创建出对话框对象
        AlertDialog dialog = builder.create();
        dialog.show();//显示对话框
    }
}
